<?php
/**
 * MiniBlog class 
 *
 * @version 0.1 
 * @license MIT License http://www.opensource.org/licenses/mit-license.php
 * @copyright (c) 2007 Geir Arne Brevik
 * @author Geir Arne Brevik
 */
if (!defined('MB')) { header('Location:./'); } // prevent direct access to this file

class MiniBlog
{
	/**
	 * initialize an object of the MiniBlog class and fill it with contents form the database table
	 *
	 * @param int $id id in database table for the object we're creating
	 * @author Geir Arne
	 **/
	function __construct($id)
	{
		// database connection
		global $db, $CONFIG;
		
        // get data from the class' corresponding database table
        $query = "SELECT * FROM " . $CONFIG['db_prefix'] . "posts WHERE id = " . $id; 
		$row = $db->getArray($query);
        
        // populate the object with variables
        foreach ($row as $field => $fieldvalue) {
            $this->$field = is_string($fieldvalue) ? stripslashes($fieldvalue) : $fieldvalue;
        }

		$this->permalink = $this->getPermalink();
		$this->edit_link = $this->getEditLink();
	}
	
	/**
	 * Create table for this class
	 *
	 * @author Geir Arne Brevik
	 **/
	function createTable()
	{
		global $db, $CONFIG;
		
		$query ="CREATE TABLE `" . $CONFIG['db_prefix'] . "posts` (
		  `id` int(11) NOT NULL auto_increment,
		  `title` varchar(255) default NULL,
		  `slug` varchar(255) default NULL,
		  `body` text,
		  `frontpage_allowed` tinyint(1) default 1,
		  `visible_on_frontpage` tinyint(1) default 0,
		  `created_at` datetime default NULL,
		  `updated_at` datetime default NULL,
		  `created_by` int(11) default NULL,
		  `updated_by` int(11) default NULL,
		  UNIQUE KEY `id` (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
		$db->doQuery($query);
	}
	
	
	/**
	 * get contents of this object, as an array
	 * would usually reside in a superclass
	 *
	 * @return array of mixed vars
	 * @author Geir Arne Brevik
	 **/
	function getData()
	{
		$my_data = array();
		
		foreach ($this as $key=>$value){
			if (is_array($value) and !is_object($value)) {
				foreach($value as $subkey=>$subvalue) {
					$my_data[$key][$subkey] = is_string($subvalue) ? stripslashes(strip_tags($subvalue)) : $subvalue;
				}
			} else {
				$my_data[$key] = is_string($value) ? stripslashes(strip_tags($value)) : $value;
			}
		}
		return $my_data;
	}
	
	
	/**
	 * Save new and/or edit blogpost
	 *
	 * @return void
	 * @author Geir Arne Brevik
	 **/
	function save($values, $edit)
	{
		global $db, $CONFIG, $NOW, $current_user;
		
		$result = array();
		
		foreach ($values as $key=>$value){
			$result['values'][$key] = strip_tags($value);
			$$key = mysqli_real_escape_string($db->link, strip_tags($value));
		}
		// verify input
		if (!$title or !$body) {
			$result['errors'] = 'Please fill inn all fields.';
		}
		
		if (!$result['errors']) {
			$author_id = $current_user;
			
			// update database
			if ($edit) {
				$query = "UPDATE " . $CONFIG['db_prefix'] . "posts SET title = ('$title'), body = ('$body'), frontpage_allowed = ('$frontpage_allowed'), updated_at = ('$NOW'), updated_by = ('$author_id') WHERE id = " . $id;
				// do the query
				$db->doQuery($query);
			} else { // or save new
				// get slug, clean variant of the title to be used in URI
				$slug = getNewSlug($title, 'posts');

				$query = "INSERT INTO " . $CONFIG['db_prefix'] . "posts (title, slug, body, frontpage_allowed, created_at, updated_at, created_by, updated_by) VALUES ('$title', '$slug', '$body', '$frontpage_allowed', '$NOW', '$NOW', '$author_id', '$author_id')";				
				// do the query
				$db->doQuery($query);
				// redirect to edit
				header('Location:save.php?s='.$slug);
			}
		}
		
		return($result);
	}
	
	
	/**
	 * return array of post objects
	 *
	 * @return array of objects, or bool false if none
	 * @author Geir Arne Brevik
	 **/
	public function index($args = array())
	{
		global $CONFIG, $db;
		
		$defaults = array('show_user'=>false,				// show only posts by this user - ID
						  'frontpage_allowed'=>false, 		// show only posts that are allowed to be promoted to the frontpage
						  'visible_on_frontpage'=>false 	// show only posts that are promoted to the frontpage
						  );
		// override default options with supplied arguments
		foreach($args as $arg_key=>$arg_value){ $defaults[$arg_key] = $arg_value; }
		// make readable local variables
		foreach($defaults as $opt_key=>$opt_value){ $$opt_key = $opt_value; }
		
		$blogposts = array();
		
		// get ids for the posts
		$query = "SELECT id FROM ".$CONFIG['db_prefix']."posts ".(
				  ($show_user or $frontpage_allowed or $visible_on_frontpage) ?
					"WHERE ".
					($show_user ? "created_by = ".$show_user." " : "").
					(($frontpage_allowed and !$visible_on_frontpage) ? ($show_user ? "AND " : "")."frontpage_allowed = 1 " : "").
					($visible_on_frontpage ? ($show_user ? "AND " : "")."visible_on_frontpage = 1 AND frontpage_allowed = 1 " : "")
					: ""
				  )."ORDER BY created_at DESC";
		$post_ids = $db->doQuery($query);

		// loop through the mysql resultset, create object(s), and add to the array
		while ($row = mysqli_fetch_assoc($post_ids)) {
			$post = new MiniBlog($row['id']);
			array_push($blogposts, $post);
		}
		
		// return results
		if (count($blogposts) == 0) {
			return(false);
		} else {
			return($blogposts);
		}
	}

	
	/**
	 * Set one field, and one field only, wether the blogpost is visible on the frontpage
	 *
	 * @param array $values The values submitted from the form
	 * @author Geir Arne Brevik
	 **/
	function setFrontpageStatus($values)
	{
		global $db, $CONFIG, $NOW;
		
		foreach ($values as $key=>$value){
			$result['values'][$key] = strip_tags($value);
			$$key = mysqli_real_escape_string($db->link, strip_tags($value));
		}
		
		$query = "UPDATE " . $CONFIG['db_prefix'] . "posts SET visible_on_frontpage = ('$visible_on_frontpage'), updated_at = ('$NOW'), updated_by = ('$author_id') WHERE id = " . $id;
		// do the query
		$db->doQuery($query);
	}
	
	/**
	 * Get all authors that have published a blogpost
	 *
	 * @return array $authors ids for authors | bool false
	 * @author Geir Arne Brevik
	 **/
	function getAuthors()
	{
		global $CONFIG, $db;
		
		$authors = array();
		
		$query = "SELECT DISTINCT created_by FROM ".$CONFIG['db_prefix']."posts ORDER BY created_by ASC";
		$author_ids = $db->doQuery($query);
		
		// 
		while ($row = mysqli_fetch_assoc($author_ids)) {
			array_push($authors, $row['created_by']);
		}
		
		if (count($authors) == 0) {
			return(false);
		} else {
			return($authors);
		}
	}
	
	
	/**
	 * Check if a given author exists
	 *
	 * @param int $author user id (or something we presume to be user id)
	 * @return bool
	 * @author Geir Arne Brevik
	 **/
	function authorExists($author)
	{
		global $CONFIG, $db;
		
		if(is_numeric($author)){
			$query = "SELECT COUNT(*) FROM ".$CONFIG['db_prefix']."posts WHERE created_by = ".$author;
			return(($db->getFirstInArray($query) == 0) ? false : true);
		} else {
			return(false);
		}
	}
	
	/**
	 * Delete blogpost
	 *
	 * @param array $values Values sent by form
	 * @author Geir Arne Brevik
	 **/
	function delete($values)
	{
		global $db, $CONFIG;
		
		foreach ($values as $key=>$value){
			$$key = mysqli_real_escape_string($db->link, strip_tags($value));
		}
		
		$query = "DELETE FROM ".$CONFIG['db_prefix']."posts WHERE id = ".$id;
		$db->doQuery($query);
	}
	
	
	/**
	 * Return permalink
	 *
	 * @return string string relative url path for showing the object
	 * @author Geir Arne Brevik
	 **/
	private function getPermalink()
	{
		// ::TODO:: make this independent of file names and -structure
		return('./show.php?s='.$this->slug);
	}
	
	/**
	 * Return edit link
	 *
	 * @return string relative url path for editing the object
	 * @author Geir Arne Brevik
	 **/
	private function getEditLink()
	{
		// ::TODO:: make this independent of file names and -structure
		return('./save.php?s='.$this->slug);
	}
}

?>